import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class StudentUpdater:
    def __init__(self):
        self.db = Database()
    
    def update_student(self, student_id, name=None, gender=None, class_name=None, contact=None):
        """
        更新学生信息
        
        参数:
            student_id (str): 学号
            name (str, optional): 新的姓名
            gender (str, optional): 新的性别
            class_name (str, optional): 新的班级
            contact (str, optional): 新的联系方式
        
        返回:
            bool: 更新成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not student_id:
                print("错误：学号必须提供")
                return False
            
            if gender is not None and gender not in ['男', '女']:
                print("错误：性别必须是'男'或'女'")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查学生是否存在
            self.db.cursor.execute(
                "SELECT id, name, gender, class_name, contact FROM student WHERE student_id = ?",
                (student_id,)
            )
            student = self.db.cursor.fetchone()
            
            if not student:
                print(f"错误：学号为 {student_id} 的学生不存在")
                return False
            
            student_db_id, old_name, old_gender, old_class_name, old_contact = student
            
            # 构建更新语句
            update_fields = []
            params = []
            
            if name is not None:
                update_fields.append("name = ?")
                params.append(name)
            
            if gender is not None:
                update_fields.append("gender = ?")
                params.append(gender)
            
            if class_name is not None:
                update_fields.append("class_name = ?")
                params.append(class_name)
            
            if contact is not None:
                update_fields.append("contact = ?")
                params.append(contact)
            
            if not update_fields:
                print("没有提供需要更新的字段")
                return False
            
            # 执行更新
            query = f"UPDATE student SET {', '.join(update_fields)} WHERE id = ?"
            params.append(student_db_id)
            
            self.db.cursor.execute(query, params)
            self.db.conn.commit()
            
            # 获取更新后的信息
            self.db.cursor.execute(
                "SELECT name, gender, class_name, contact FROM student WHERE id = ?",
                (student_db_id,)
            )
            new_info = self.db.cursor.fetchone()
            new_name, new_gender, new_class_name, new_contact = new_info
            
            print(f"成功：学生 {old_name}（学号：{student_id}）信息已更新")
            if name is not None:
                print(f"  姓名: {old_name} -> {new_name}")
            if gender is not None:
                print(f"  性别: {old_gender} -> {new_gender}")
            if class_name is not None:
                print(f"  班级: {old_class_name} -> {new_class_name}")
            if contact is not None:
                old_contact_display = old_contact if old_contact else "无"
                new_contact_display = new_contact if new_contact else "无"
                print(f"  联系方式: {old_contact_display} -> {new_contact_display}")
            
            return True
        except Exception as e:
            print(f"错误：更新学生信息时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    updater = StudentUpdater()
    
    print("===== 学生信息更新 =====")
    
    # 先查询所有学生
    from query_student import StudentQuery
    query = StudentQuery()
    students = query.query_all_students()
    
    if not students:
        print("没有找到任何学生信息")
    else:
        print("\n学生ID\t学号\t姓名\t性别\t班级\t联系方式\t宿舍ID")
        for student in students:
            dormitory_id = student[6] if student[6] else "未分配"
            print(f"{student[0]}\t{student[1]}\t{student[2]}\t{student[3]}\t{student[4]}\t{student[5] or '无'}\t{dormitory_id}")
        
        student_id = input("\n请输入要更新的学生学号: ")
        
        print("\n请选择要更新的信息（不更新的项目请留空）:")
        name = input("新姓名: ")
        gender = input("新性别 (男/女): ")
        class_name = input("新班级: ")
        contact = input("新联系方式: ")
        
        # 处理空输入
        if not name:
            name = None
        if not gender:
            gender = None
        if not class_name:
            class_name = None
        if not contact:
            contact = None
        
        if name or gender or class_name or contact:
            updater.update_student(student_id, name, gender, class_name, contact)
        else:
            print("没有提供任何更新信息")